package com.eqdd.yiqidian.ui.mine.pizhun;

import android.databinding.DataBindingUtil;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.eqdd.yiqidian.NoticeInfoActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.ChangeShiftInfoResultBean;
import com.eqdd.yiqidian.bean.rebuild.LeaveCheckerListResultBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditApplyTitleBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditHintBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.functions.BiFunction;
import io.reactivex.subscribers.DisposableSubscriber;

public class ChangeShiftInfoActivity extends BaseActivity {
    private NoticeInfoActivityCustom dataBinding;
    private SlimAdapterEx<SlimEditBean> slimAdapterEx;
    private String changeShiftId;
    private ArrayList<SlimEditBean> datas;
    private ChangeShiftInfoResultBean items;
    private List<LeaveCheckerListResultBean> checkers;
    private int who;
    private int status;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_notice_info);
        initTopTitleBar(View.VISIBLE, "调班详情");
    }

    @Override
    public void initData() {
        changeShiftId = getIntent().getStringExtra("changeShiftId");
        who = getIntent().getIntExtra(Config.WHO, 0);
        status = getIntent().getIntExtra(Config.STATUS, -1);
        initTitle();
        datas = new ArrayList<>();
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterEx = SlimAdapterEx.create()
                .register(R.layout.list_item_49, new SlimInjector<SlimEditApplyTitleBean>() {
                    @Override
                    public void onInject(SlimEditApplyTitleBean data, IViewInjector injector) {
                        injector.text(R.id.tv_upper_left_content, dealText(data.getTopLeftContent()))
                                .text(R.id.tv_upper_right_content, dealText(data.getTopRightContent()))
                                .text(R.id.tv_down_content, dealText(data.getTitle()));

                    }
                })
                .register(R.layout.list_item_28, new SlimInjector<SlimEditHintBean>() {
                    @Override
                    public void onInject(SlimEditHintBean data, IViewInjector injector) {
                        injector.text(R.id.tv_left_content, dealText(data.getTitle()))
                                .text(R.id.tv_right_hint_content, dealText(data.getContent()));
                    }
                }).attachTo(dataBinding.recyclerView);
        dataBinding.rbReject.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                dataBinding.rbAgree.setChecked(!isChecked);
            }
        });
        dataBinding.rbAgree.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                dataBinding.rbReject.setChecked(!isChecked);
            }
        });
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    switch (slimAdapterEx.getDataItem(position).getPosition()) {

                    }
                });
    }

    private void initTitle() {
        if (status == 0 && who >= 1) {
            initTopRightText("提交", v -> {
                if (checkParam()) {
                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + (who == 2 ? HttpConfig.CHANGE_SHIFT_CHECK_BY_HR : HttpConfig.CHANGE_SHIFT_CHECK))
                            .params("changeShiftId", items.getId())
                            .params("userGuid", user.getGuid())
                            .params("message", dealText(dataBinding.etRemark.getText().toString()))
                            .params("type", dataBinding.rbAgree.isChecked() ? 1 : 2)
                            .execute(new DialogCallBack<HttpResult>(this) {
                                @Override
                                public void onSuccess(Response<HttpResult> response) {
                                    HttpResult httpResult = response.body();
                                    ToastUtil.showShort(httpResult.getMsg());
                                    if (httpResult.getStatus() == 200) {
                                        setResult(Config.SUCCESS);
                                        finish();
                                    }
                                }
                            });
                } else {
                    ToastUtil.showLong("真残忍，能否给个理由先？");
                }
            });
        }
    }

    private boolean checkParam() {
        return !(dataBinding.rbReject.isChecked() && TextUtils.isEmpty(dataBinding.etRemark.getText()));
    }

    @Override
    public void setView() {
        Flowable<HttpResult<List<LeaveCheckerListResultBean>>> flowLeaveChecker = OkGo.<HttpResult<List<LeaveCheckerListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.CHANGE_SHIFT_CHECKER_LIST)
                .params("changeShiftId", changeShiftId)
                .converter(new JsonConverter<HttpResult<List<LeaveCheckerListResultBean>>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<List<LeaveCheckerListResultBean>>>());

        Flowable<HttpResult<ChangeShiftInfoResultBean>> flowLeaveInfo = OkGo.<HttpResult<ChangeShiftInfoResultBean>>post(HttpConfig.BASE_URL + HttpConfig.CHANGE_SHIFT_INFO)
                .params("changeShiftId", changeShiftId)
                .converter(new JsonConverter<HttpResult<ChangeShiftInfoResultBean>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<ChangeShiftInfoResultBean>>());
        Flowable.combineLatest(flowLeaveChecker, flowLeaveInfo, (BiFunction<HttpResult<List<LeaveCheckerListResultBean>>, HttpResult<ChangeShiftInfoResultBean>, Object>) (listHttpResult, changeShiftInfoResultBeanHttpResult) -> {
            if (changeShiftInfoResultBeanHttpResult.getStatus() == 200) {
                items = changeShiftInfoResultBeanHttpResult.getItems();
                if (items == null) {
                    if (!dispos.isDisposed()) {
                        dispos.dispose();
                    }
                    ToastUtil.showShort("单子已删除");
                    finish();
                }
            }
            if (listHttpResult.getStatus() == 200) {
                checkers = listHttpResult.getItems();

            }
            return 1;
        })
                .subscribe(dispos);

    }

    private DisposableSubscriber dispos = new DisposableSubscriber() {
        @Override
        public void onNext(Object o) {
            datas.add(new SlimEditHintBean(items.getCreaterName(), items.getDepartment() + items.getPost(), 0));
            datas.add(new SlimEditHintBean("调班单编码", items.getChangeShiftCode(), 1));
            datas.add(new SlimEditHintBean("调班原因", items.getChangeShiftReason(), 2));
            datas.add(new SlimEditApplyTitleBean("所在班别", items.getNowRule().getRule(), getTime(items.getNowRule()), "", 3));
            datas.add(new SlimEditApplyTitleBean("要调班别", items.getChangeRule().getRule(), getTime(items.getChangeRule()), "", 4));
            for (LeaveCheckerListResultBean checker : checkers) {
                datas.add(new SlimEditApplyTitleBean(checker.getUname(), checker.getStatus() == -1 ? "等待审核" : checker.getStatus() == 2 ? "已拒绝" : "已同意",
                        checker.getMessage(), "", 5));
            }
            slimAdapterEx.updateData(datas);
            if (status == 0 && who >= 1) {
                dataBinding.llDownRoot.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {

        }
    };

    private String getTime(ChangeShiftInfoResultBean.RuleBean nowRule) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(nowRule.getStartTime1().substring(0, 5)).append("~").append(nowRule.getEndTime1().substring(0, 5)).append(" ");
        if (!(nowRule.getStartTime2().equals("00:00:00") && nowRule.getEndTime2().equals("00:00:00"))) {
            stringBuilder.append(nowRule.getStartTime2().substring(0, 5)).append("~").append(nowRule.getEndTime2().substring(0, 5)).append(" ");
            if (!(nowRule.getStartTime3().equals("00:00:00") && nowRule.getEndTime3().equals("00:00:00"))) {
                stringBuilder.append(nowRule.getStartTime3().substring(0, 5)).append("~").append(nowRule.getEndTime3().substring(0, 5)).append(" ");
                if (!(nowRule.getStartTime4().equals("00:00:00") && nowRule.getEndTime4().equals("00:00:00"))) {
                    stringBuilder.append(nowRule.getStartTime4().substring(0, 5)).append("~").append(nowRule.getEndTime4().substring(0, 5)).append(" ");
                }
            }
        }
        return stringBuilder.toString();
    }

    private String dealText(String text) {
        return TextUtils.isEmpty(text) ? " " : text;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }
}
